import { Messages } from "../protobuf/Messages";
import { httpManager } from "./Http";
import { userManager } from "./UserManager";

// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class Login extends cc.Component 
{
    @property(cc.EditBox)
    public userNameEdit: cc.EditBox = null;
    @property(cc.EditBox)
    public pswEdit: cc.EditBox = null;
    @property(cc.Button)
    public loginBtn: cc.Button = null;


    start () 
    {
    
    }

    private onClickLoginBtn()
    {
        if (this.userNameEdit.string == '' || this.pswEdit.string == '') {
            cc.error('用户名和密码不能为空！');
            return;
        }

        this.RequestLogin();
    }

    private RequestLogin()
    {
        let requestBuffer = Messages.LoginRequest.encode({userName: this.userNameEdit.string, psw: this.pswEdit.string}).finish();
        httpManager.request('/login', requestBuffer, Messages.LoginRespone.decode, (data: any) => {
            if (httpManager.checkResponseData(data)) {
                let response: Messages.LoginRespone = data as Messages.LoginRespone;
                cc.log('用户ID：' + response.uid);
                userManager.uid = response.uid;
                userManager.userName = this.userNameEdit.string;
            }
        });
    }
}
